package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.anno.CacheFind;
import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.ItemCat;
import com.jt.util.ObjectMapperUtil;
import com.jt.vo.EasyUITree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemCatServiceImpl implements ItemCatService{

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Autowired(required = false)
    private Jedis jedis;


    @Override
    public String findItemCatName(Long itemCatId) {

        return itemCatMapper.selectById(itemCatId).getName();
    }


   @Override
    public List<EasyUITree> findItemCatCache(Long parentId) {
        Long startTime = System.currentTimeMillis();
        List<EasyUITree> treeList = new ArrayList<>();
        String key = "ITEMCAT::" + parentId;
        if(jedis.exists(key)){
            String json = jedis.get(key);
            treeList = ObjectMapperUtil.toObject(json, treeList.getClass());
            Long endTime = System.currentTimeMillis();
            System.out.println("redis缓存查询数据的时间" + (endTime-startTime));
        }else {
            treeList = findItemCatList(parentId);
            String json = ObjectMapperUtil.toJSON(treeList);
            jedis.set(key,json);
            Long endTime = System.currentTimeMillis();
            System.out.println("查询数据库的时间" + (endTime-startTime));
        }
        return treeList;
    }


    @CacheFind(preKey="ITEMCAT_PARENTID")
    @Override
    public List<EasyUITree> findItemCatList(Long parentId) {
        //1.准备返回值数据
        List<EasyUITree> treeList = new ArrayList<>();
        //思路.返回值的数据从哪来? VO  转化 POJO数据

        //2.实现数据库查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",parentId);
        List<ItemCat> catList = itemCatMapper.selectList(queryWrapper);

        //3.实现数据的转化  catList转化为 treeList
        for (ItemCat itemCat : catList){
            long id = itemCat.getId();  //获取ID值
            String text = itemCat.getName();    //获取商品分类名称
            //判断:如果是父级 应该closed  如果不是父级 则open
            String state = itemCat.getIsParent()?"closed":"open";
            EasyUITree easyUITree = new EasyUITree(id,text,state);
            treeList.add(easyUITree);
        }

        return treeList;
    }
}
